package ir.values.users.instructions;

import frontend.visitor.symboltbl.scope.Scope;
import ir.types.datatypes.VoidType;
import ir.values.FunctionIr;
import ir.values.Value;

import java.util.ArrayList;

public class CallInst extends Instruction {

    private final FunctionIr functionIr;
    private final ArrayList<Value> args;

    public CallInst(FunctionIr functionIr, ArrayList<Value> args) {
        super(null, functionIr.getReturnType());
        this.functionIr = functionIr;
        this.args = args;
        operands.add(functionIr);
        operands.addAll(args);
    }

    @Override
    public InstOperator getInstOperator() {
        return InstOperator.call;
    }
    @Override
    public boolean shouldGenerateId() {
        return !(functionIr.getReturnType() instanceof VoidType);
    }
    @Override
    public String parseLLVM() {
        // eg: %1 = call i32 @func(i32 1, i32 2)
        StringBuilder sb = new StringBuilder();
        if (shouldGenerateId()) {
            sb
                    .append(parseUsingName())
                    .append(" = ");
        }
        sb
                .append(getInstOperator())
                .append(" ")
                .append(type.toString())
                .append(" ")
                .append(functionIr.parseUsingName())
                .append("(");
        for (int i = 0; i < args.size(); i++) {
            Value arg = args.get(i);
            sb
                    .append(arg.getType().toString())
                    .append(" ")
                    .append(arg.parseUsingName());
            if (i != args.size() - 1) {
                sb.append(", ");
            }
        }
        sb.append(")");
        return sb.toString();
    }
}
